<template>
  <div class="user-profile-edit">
    <!-- 导航栏 -->
    <van-nav-bar
      left-text="返回"
      left-arrow
      @click-left="goBack"
      title="修改个人资料"
    />

    <!-- 表单 -->
    <van-form @submit="handleSubmit" ref="form">
      <!-- 姓名 -->
      <van-field
        v-model="user.name"
        label="姓名"
        placeholder="请输入姓名"
        clearable
      />

      <!-- 图片上传 -->
      <van-field name="uploader" label="头像上传">
        <template #input>
          <van-uploader
            v-model="fileList"
            :after-read="onImageChange"
            :max-count="1"
          >
            <template #preview="image">
              <van-image
                :src="image.file.url"
                @click="showPreview(image.file)"
              />
              <van-icon name="cross" @click="onDeleteImage(image.file)" />
            </template>
          </van-uploader>
        </template>
      </van-field>

      <!-- 性别 -->
      <van-field
        v-model="user.sex"
        label="性别"
        placeholder="请选择性别"
        readonly
        clickable
        @click="showGenderPicker = true"
      />

      <!-- 电话 -->
      <van-field
        v-model="user.phone"
        label="电话"
        placeholder="请输入电话"
        type="tel"
        clearable
      />

      <!-- 邮箱 -->
      <van-field
        v-model="user.email"
        label="邮箱"
        placeholder="请输入邮箱"
        clearable
      />

      <!-- 学号 -->
      <van-field
        v-model="user.studentId"
        label="学号"
        placeholder="请输入学号"
        clearable
      />

      <!-- 入学年份 -->
      <van-field
        v-model="user.enrollmentYear"
        label="入学年份"
        placeholder="请选择入学年份"
        readonly
        clickable
        @click="showYearPicker = true"
      />

      <!-- 院系 -->
      <van-field
        v-model="user.faculty"
        label="院系"
        placeholder="请输入院系"
        clearable
      />

      <!-- 保存按钮 -->
      <van-button type="primary" native-type="submit" block>保存</van-button>
    </van-form>
  </div>
</template>


<script>
import { Field, Button, Picker, Popup, Form, NavBar, Uploader } from "vant";
import userProfileApi from "@/api/userProfile.js";
import fileApi from "@/api/file.js";

export default {
  components: {
    "van-field": Field,
    "van-button": Button,
    "van-picker": Picker,
    "van-popup": Popup,
    "van-form": Form,
    "van-nav-bar": NavBar,
    "van-uploader": Uploader,
  },
  data() {
    return {
      user: {
        name: "",
        sex: "",
        phone: "",
        email: "",
        studentId: "",
        enrollmentYear: "",
        faculty: "",
        pic: "", // 存储头像的字段
      },
      genderOptions: ["男", "女"],
      yearOptions: Array.from({ length: 10 }, (_, i) => (2024 - i).toString()), // 生成过去10年的年份
      showGenderPicker: false,
      showYearPicker: false,
      fileList: [], // 用于存储上传的文件列表
    };
  },
  mounted() {
    // 获取原有资料
    this.getUserProfile();
  },
  methods: {
    onDeleteImage(file, index, fileList) {
      const objectName = this.getObjectName(file);
      if (objectName) {
        fileApi.deleteImage(objectName).then(()=>{
          this.fileList = [];
          this.user.pic = "";
        })
      } else {
        this.$toast.fail("无法获取图片名称，删除失败");
      }
    },
    getObjectName(file) {
      if (file && file.url) {
        // 假设URL是'http://your-oss-bucket.com/path/to/objectName.jpg'
        // 需要提取'path/to/objectName.jpg'
        const url = file.url;
        const bucketUrl = "https://volunteersystem.oss-cn-beijing.aliyuncs.com/"; // 替换为你的OSS bucket URL
        const objectName = url.replace(bucketUrl, "");
        return objectName;
      }
      return null;
    },
    getUserProfile() {
      userProfileApi.getUserProfile(this.user).then((res) => {
        this.user = res;
        if (this.user.pic) {
          this.fileList = [{ url: this.user.pic }];
        }
      });
    },

    // 提交表单
    async handleSubmit() {
      try {
        console.log("提交的数据:", this.user);
        // 调用 API 更新用户资料
        await userProfileApi.updateUserProfile(this.user);
        this.$toast.success("资料已保存");
        this.getUserProfile();
      } catch (err) {
        console.error(err);
        this.$toast.fail(err.message || "更改失败");
      }
    },

    // 处理图片上传
    onImageChange(fileObj) {
      const file = fileObj.file;
      console.log("上传的图片文件:", file);
      if (file && file instanceof File) {
        console.log("上传的文件类型:", file.type);
        fileApi.fileUpload(file).then((res) => {
          console.log(res);
          this.user.pic = res;
          this.fileList = [
            {
              file: file,
              url: res,
            },
          ];
          console.log(this.user);
        });
      } else {
        console.error("上传的文件无效");
      }
    },

    // 性别选择器
    onGenderConfirm(value) {
      this.user.sex = value;
      this.showGenderPicker = false;
    },
    onGenderCancel() {
      this.showGenderPicker = false;
    },

    // 入学年份选择器
    onYearConfirm(value) {
      this.user.enrollmentYear = value;
      this.showYearPicker = false;
    },
    onYearCancel() {
      this.showYearPicker = false;
    },

    // 返回上一页
    goBack() {
      this.$router.go(-1); // 使用 Vue Router 返回上一页
    },
  },
};
</script>

<style scoped>
.van-nav-bar ::v-deep .van-nav-bar__text,
.van-nav-bar ::v-deep .van-nav-bar__title {
  color: white !important;
}

.van-nav-bar ::v-deep .van-nav-bar__arrow{
  color: white !important;
}
.user-profile-edit {
  padding: 5vh 5%;
  background-color: #f8f9fa;
  min-height: 100vh;
  box-sizing: border-box;
}

/* 导航栏 */
.van-nav-bar {
  margin-bottom: 3vh;
  background-color: #007aff;
  color: white;
}

/* 输入框样式 */
.van-field {
  margin-bottom: 2vh;
  background-color: white;
  border-radius: 0.5vh;
  padding: 1.5vh;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 输入框标签样式 */
.van-field__label {
  color: #007aff;
  font-weight: bold;
  font-size: 2.5vh;
}

/* 输入框内容样式 */
.van-field__control {
  font-size: 2.5vh;
  color: #333;
}

/* 上传组件 */
.van-uploader {
  margin-top: 1vh;
}

.van-uploader__preview {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.van-uploader__preview-img {
  width: 100%;
  max-width: 15vh;
  border-radius: 0.5vh;
  margin-bottom: 1vh;
}

.van-uploader__preview-delete {
  margin-top: -2vh;
  background-color: #ff4d4f;
  border-radius: 50%;
  width: 2.5vh;
  height: 2.5vh;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  font-size: 2vh;
}

/* 按钮样式 */
.van-button {
  margin-top: 3vh;
  font-size: 2.5vh;
  background-color: #007aff;
  color: white;
  border-radius: 2vh;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

/* 响应式调整 */
@media (max-width: 767px) {
  .van-field__label,
  .van-field__control,
  .van-button {
    font-size: 3vh;
  }
  .van-uploader__preview-img {
    max-width: 20vh;
  }
}

@media (min-width: 768px) {
  .van-field__label,
  .van-field__control,
  .van-button {
    font-size: 2vh;
  }
}
</style>
